var mongoose=require('mongoose');
const User=require('../model/user.model');

//增
exports.create=function(req,res,next){
    const user=new User(req.body);
    //实例化对象，req.body代表是post的数据提交，并且参数从body中获取
	user.save().then(data=>{
        //数据保存，在保存以后将数据用json形式进行输出
        res.json(data)
        console.log(data);
	});
};

//删
exports.remove=function(req,res,next){
	var id=req.params.id;
	User.findByIdAndRemove(id,function(err,data){
		res.json({message:'删除成功'});
	});
};

//改
exports.update=function(req,res,next){
    //先找到一个id值
	var id=req.params.id;
	User.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
		res.json(data);
	
	});
};
exports.list = function (req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 5;
    var queryCondition = {};

    if (req.body.title && req.body.title.trim().length > 0) {
        title = req.body.title;
        queryCondition = {
            title: new RegExp(title, 'i')
        }
    }

    if (req.body.cateId && req.body.cateId.trim().length > 0) {
        cateId = req.body.cateId;
        queryCondition = Object.assign(queryCondition, {
            cateId: cateId
        })
    }

    User.paginate(queryCondition, { page: +page, limit: +rows }, function (err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
}
//
// exports.getIData = function(req,res,next){
// 	const id = req.params.id;
// 	Uews.findById(id,function(err,data){
// 			res.json(data);
// 	})
// };

//
exports.getIData = function(req,res,next){
	const id = req.params.id;
	User.findById(id,function(err,data){
			res.json(data);
	})
};
//删除多个
exports.removes=function(req,res,next){
	var ids=req.body.ids;
	//ids=ids.split(",");
	
	if(ids.length>0){
		User.remove({_id:{$in:ids}}).then(data =>{
			res.json({"message":"多条记录删除成功"})
		})
		
	}
};



// //shanchuduoge
// exports.removes=function(req,res,next){
// 	var ids=req.body.ids;
// 	ids=ids.split(",");
	
// 	if(ids.length>0){
// 		User.remove({_id:{$in:ids}}).then(data =>{
// 			res.json({"message":"多条记录删除成功"})
// 		})
		
// 	}
//}
